<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace app\portal\controller;

use api\home\model\SlideItemModel;
use app\portal\model\QuestionsModel;
use app\user\model\UserModel;
use cmf\controller\HomeBaseController;
use app\portal\model\PortalCategoryModel;
use app\portal\service\PostService;
use app\portal\model\PortalPostModel;
use think\facade\Lang;

class ArticleController extends HomeBaseController
{
    /**
     * 文章详情
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $lang = session('Lang');
        if ($lang){
            Lang::setLangSet($lang);
            if ($lang == 'us'){
                $langType = '1';
            }
        }

        $portalCategoryModel = new PortalCategoryModel();
        $postService         = new PostService();

        $articleId  = $this->request->param('id', 0, 'intval');
        $categoryId = $this->request->param('cid', 0, 'intval');
        $article    = $postService->publishedArticle($articleId, $categoryId);

        if (empty($article)) {
            abort(404, '文章不存在!');
        }


        $prevArticle = $postService->publishedPrevArticle($articleId, $categoryId);
        $nextArticle = $postService->publishedNextArticle($articleId, $categoryId);

        $tplName = 'article';

        if (empty($categoryId)) {
            $categories = $article['categories'];

            if (count($categories) > 0) {
                $this->assign('category', $categories[0]);
            } else {
                abort(404, '文章未指定分类!');
            }

        } else {
            $category = $portalCategoryModel->where('id', $categoryId)->where('status', 1)->find();

            if (empty($category)) {
                abort(404, '文章不存在!');
            }

            $this->assign('category', $category);

            $tplName = empty($category["one_tpl"]) ? $tplName : $category["one_tpl"];
        }

        PortalPostModel::where('id', $articleId)->inc('post_hits')->update();


        hook('portal_before_assign_article', $article);

        $this->assign('article', $article);
        $this->assign('prev_article', $prevArticle);
        $this->assign('next_article', $nextArticle);

        $tplName = empty($article['more']['template']) ? $tplName : $article['more']['template'];



        $portalPostModel = new PortalPostModel();
        $articleList = $portalPostModel->alias('post')->field('post.*')
            ->join('portal_category_post relation', 'post.id = relation.post_id')
            ->where('post.show_hot',1)
            ->limit(8)
            ->order('relation.list_order desc,update_time desc')
            ->select();


        $this->assign('nav', 'article');
        $this->assign('articleList', $articleList);

        $is_mobile = cmf_is_mobile();

        if ($is_mobile == true){

            return $this->fetch(':mobile_article');
        }else{
            return $this->fetch("/$tplName");
        }



    }


    public function info(){

        $lang = session('Lang');
        if ($lang){
            Lang::setLangSet($lang);
        }

        // 幻灯片
        $slideModel = new SlideItemModel();
        $where = [];
        $where[] = ['status','=','1'];
        $where[] = ['slide_id','=','2'];
        $slide_list = $slideModel->where($where)->order('list_order desc')->select();


        $portalCategoryModel = new PortalCategoryModel();
        $postService         = new PostService();

        $articleId  = $this->request->param('id', 0, 'intval');
        $categoryId = $this->request->param('cid', 0, 'intval');
        $article    = $postService->publishedArticle($articleId, $categoryId);

        PortalPostModel::where('id', $articleId)->inc('post_hits')->update();

        $this->assign('slide_list', $slide_list);
        $this->assign('article', $article);
        $this->assign('nav', 'article');

        $more = isset($article['more']['photos'][0]['url']) ? $article['more']['photos'][0]['url'] : '';


        $brand_title = $article['brand_title'];
        $brand_title_list = explode(',',$brand_title);

        $this->assign('brand_title_list', $brand_title_list);
        $this->assign('more', $more);

        $is_mobile = cmf_is_mobile();
        if ($is_mobile == true){

            return $this->fetch(':mobile_info');
        }else{
            return $this->fetch(':info');
        }

    }

    // 文章点赞
    public function doLike()
    {
        $this->checkUserLogin();
        $articleId = $this->request->param('id', 0, 'intval');


        $canLike = cmf_check_user_action("posts$articleId", 1);

        if ($canLike) {
            PortalPostModel::where('id', $articleId)->inc('post_like')->update();

            $this->success("赞好啦！");
        } else {
            $this->error("您已赞过啦！");
        }
    }

    public function teacher(){
        $id = $this->request->param('id','');
        $page = $this->request->param('page','1');
        $lang = session('Lang');
        if ($lang){
            Lang::setLangSet($lang);
        }

        // 幻灯片
        $slideModel = new SlideItemModel();
        $where = [];
        $where[] = ['status','=','1'];
        $where[] = ['slide_id','=','2'];
        $slide_list = $slideModel->where($where)->order('list_order desc')->select();


        $portalCategoryModel = new PortalCategoryModel();
        $postService         = new PostService();

        $articleId  = $this->request->param('id', 0, 'intval');
        $categoryId = $this->request->param('cid', 0, 'intval');
        $article    = $postService->publishedArticle($articleId, $categoryId);

        PortalPostModel::where('id', $articleId)->inc('post_hits')->update();


        $questionsModel = new QuestionsModel();
        $where = [];
        $where[] = ['answer','not null',''];
        $where[] = ['status','=',1];
        if ($id){
            $where[] = ['q_id','=',$id];
        }
        $list = $questionsModel->where($where)->page($page)->limit(10)->select();

        $total = $questionsModel->where($where)->count();


        $this->assign('slide_list', $slide_list);
        $this->assign('article', $article);
        $this->assign('nav', 'article');
        $this->assign('list', $list);
        $this->assign('id', $id);
        $this->assign('total', $total);


        $pagination = $this->getKefuPagination($page,count($list));

        $this->assign('pagination', $pagination);

        $is_mobile = cmf_is_mobile();
        if ($is_mobile == true){

            return $this->fetch(':mobile_teacher');
        }else{
            return $this->fetch(':teacher');
        }

    }


    public function addAnswer(){
        $description      = $this->request->param('recipient', '');
        $id               = $this->request->param('id', '');

        if (!$description){
            $this->error('请输入内容');
        }

        $user_id = cmf_get_current_user_id();
        $questionsModel = new QuestionsModel();
        $update = [];
        $update['user_id'] = $user_id;
        $update['description'] = $description;
        $update['type'] = 2;
        $update['status'] = 1;
        $update['create_time'] = time();
        $update['q_id'] = $id;
        $questionsModel->insertGetId($update);

        $this->success('提问成功，请等待回复');


    }


    /**
     * 分页封装
     */
    public function getKefuPagination($page=1,$total=0){
        $url = $_SERVER['REQUEST_URI'];
        $nextPage = $page+1;
        $upPage =  $page -1 ;

        $pages = '';

        //
       // ' <ul class="pagination1"><li class="page-item disabled"><span class="page-link">«</span></li> <li class="active page-item disabled"><span class="page-link">1</span></li><li class="page-item"><a class="page-link" href="/portal/admin_article/index.html?page=2">2</a></li><li class="page-item"><a class="page-link" href="/portal/admin_article/index.html?page=3">3</a></li><li class="page-item"><a class="page-link" href="/portal/admin_article/index.html?page=4">4</a></li> <li class="page-item"><a class="page-link" href="/portal/admin_article/index.html?page=2">»</a></li></ul>';


        if ($page == 1 && $total == 10){
            $nexturl = $url.'&page='.$nextPage;
            $pages = ' <ul class="pagination1">
                    <li class="page-item disabled"><span>« 上一页 </span></li>
                    <li class="active"><span>1</span></li>
                    <li><a href="'.$nexturl.'">下一页 »</a></li>
                </ul>';
        }else if ($page > 1 && $total == 10){
            $nexturl = $url.'&page='.$nextPage;
            $upurl = $url.'&page='.$upPage;
            $pages = ' <ul class="pagination1">
                    <li><span><a href="'.$upurl.'">« 上一页</a></span></li>
                    <li class="page-link"><span>'.$page.'</span></li>
                    <li class="page-link"><a href="'.$nexturl.'">下一页 »</a></li>
                </ul>';
        }elseif ($page > 1 && $total < 10){
            $upurl = $url.'&page='.$upPage;
            $pages = ' <ul class="pagination1">
                        <li><span><a href="'.$upurl.'">« 上一页</a></span></li>
                        <li class="active"><span>'.$page.'</span></li>
                        <li class="disabled" ><span>下一页 »</span></li>
                </ul>';
        }


        return $pages;

    }


}
